﻿/*
panel:flash按钮外侧容器；
fileSize:上传的文件限制大小；
IsCreateThumbnail:是否需要服务器生成缩略图
succCallBack:上传成功之后的回掉函数，可实现需要回调的功能，如显示上传后的图；
args:需要在回掉函数中回传的参数，不做任何处理，将在回掉函数中直接返回；如不需要回掉函数可直接去掉该参数；
fileCount:限制的上传文件个数
*/
function UploadFileInit(panel, fileSize, IsCreateThumbnail, succCallBack, args, fileCount) {
    // 参数是Jquey 对象
    if (panel == null || panel.length == 0) {
        return;
    }
    if ((panel instanceof jQuery) == false) {
        return;
    }
    var LoadPanel = panel;
    var PanelId = LoadPanel.attr("id");
    

    var upload;
    ///button setting
    var buttonUrl = "/Content/Admin/swfUpload/btn1.png";
    var buttonWidth = "65";
    var buttonHeight = "22";
    var buttonText = "上传图片";
    var buttontextleftpadding = 4;

    var sessionId = "";
    var fileSizeLimit = 10240;
    var fileCountLimit = 0;


    if (fileSize != null && fileSize > 0) {
        fileSizeLimit = fileSize;
    }
    if (fileCount != null && fileCount > 0) {
        fileCountLimit = fileCount;
    }
    var createThumbnail = 0;
    if (IsCreateThumbnail != null && IsCreateThumbnail > 0) {
        createThumbnail = IsCreateThumbnail;
    }

    var _addhtml = "<div style='float:left; margin-top:0px; font-size:12; '>";
    _addhtml += "<input type='text' readonly=readonly size='60' style='margin:0 5px 0 5px;width:50%;margin-top:0px; padding-top:0px;' height=22  id='Img_IUrl_" + PanelId + "' name='Img_IUrl' value='' />";
    _addhtml += "<span  id='spanButtonPlaceHolder_" + PanelId + "'></span>";
    if (fileSizeLimit > 1024) {
        _addhtml += "<span >文件不能大于" + fileSizeLimit / 1024 + "M</span><br /></div>";//<span></span>
    }
    else {
        _addhtml += "<span >文件不能大于" + fileSizeLimit + "KB</span><br /></div>";//<span></span>
    }
    
    _addhtml += "<div style='float:left;' id='fsUploadProgress_" + PanelId + "'> </div>"

    LoadPanel.append(_addhtml);

    var button_placeholder_id = "spanButtonPlaceHolder_" + PanelId;
    if (jQuery.isReady) {
        // Check to see if SWFUpload is available
        if (typeof (SWFUpload) === "undefined") {
            return;
        }
        upload = new SWFUpload({
            // Backend Settings
            upload_url: "/Home/UploadImgByWebService", // Relative to the SWF file (or you can use absolute paths)
            post_params: { "ASPSESSID": sessionId, "fileSizeLimit": fileSizeLimit, "createThumbnail": createThumbnail },


            // File Upload Settings
            file_size_limit: fileSizeLimit, // 10240  10MB
            file_types: "*.*",
            file_types_description: "All Files",
            file_upload_limit: fileCountLimit,// 文件上传数量限制
            file_queue_limit: "0",// 文件上传队列大小

            button_image_url: buttonUrl,	// Relative to the SWF file

            button_width: buttonWidth,
            button_height: buttonHeight,
            button_placeholder_id: button_placeholder_id,
            button_text: buttonText,
            //button_text_style: ".theFont { font-size: 16; text-align:center;}",
            button_text_left_padding: buttontextleftpadding,
            button_text_top_padding: 3,


            // Event Handler Settings (all my handlers are in the MultiInstanceHandlers.js file)
            file_dialog_complete_handler: fileDialogComplete,
            file_queue_error_handler: fileQueueError,
            // upload_error_handler: MultiInstanceHandlers.uploadError,
            // file_queued_handler: filequeued,
            upload_success_handler: myUploadSuccess,
            upload_progress_handler: uploadProgress,

            //debug_handler: MultiInstanceHandlers.debug,

            // Flash Settings
            flash_url: "/Content/Admin/swfUpload/swfuploadv2.20b3/swfupload.swf",//?v=" + Math.random().toString(), // Relative to this file (or you can use absolute paths)
            button_window_mode: "Opaque",//该属性可以保证IE浏览器下弹层不会出现盖不住上传按钮的问题；
            custom_settings: {
                totalProgressTarget: "uploadStatus_" + PanelId,
                lblFileStatus: "lblFileStatus_" + PanelId,
                progressTarget: "fsUploadProgress_" + PanelId,
                imgUseType: "common"
            },
            // Debug Settings
            debug: false
        });
        $('.swfupload').each(function () {
            $(this).css("vertical-align", "bottom");
        });

        // return upload;
    }

    function filequeued(file) {
        upload.customSettings.queue = upload.customSettings.queue || new Array();
        while (upload.customSettings.queue.length > 0) {
            upload.cancelUpload(upload.customSettings.queue.pop(), false);
        }
        this.customSettings.queue.push(file.id);
    }

    function fileDialogComplete(numFilesSelected, numFilesQueued) {
        try {
            upload.addPostParam("imgUseType", this.customSettings.imgUseType);
            upload.startUpload();
        }
        catch (ex) {
            upload.debug(ex);
        }
    }
    function myUploadSuccess(fileObj, server_data) {
        var progress = new FileProgress(fileObj, this.customSettings.progressTarget);
        progress.setComplete();
        progress.setStatus("上传完成.");
        progress.toggleCancel(false);
        var backData = eval("(" + server_data + ")");
        var target;
        if (backData["imgUseType"] == "common") {
            target = document.getElementById("Img_IUrl_" + PanelId);
        }
        else {
            target = document.getElementById("Img_IUrl_" + PanelId);
        }
        target.value = backData["file_url"];

        if (typeof (succCallBack) == 'function') {
            succCallBack(backData["file_url"], args);
        }
    }

    function fileQueueError(file, errorCode, message) {
        try {
            var errorName = null;

            switch (errorCode) {
                case SWFUpload.errorCode_QUEUE_LIMIT_EXCEEDED:
                    errorName = "您选择的文件数量超出了限制！"
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    errorName = "您选择了的一个文件没有数据！"
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    if (fileSizeLimit > 1024) {
                        errorName = "文件不能超过" + fileSizeLimit / 1024 + "M";
                    }
                    else {
                        errorName = "文件不能超过" + fileSizeLimit + "KB";
                    }
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    errorName = "无效的文件类型！"
                    break;
                default:
                    errorName = "您选择的文件数量超出了限制！";
                    break;
            }

            if (errorName != null) {
                alert(errorName);
                return;
            }
        } catch (ex) {
            this.debug(ex);
        }
    }

    function uploadProgress(file, bytesLoaded, bytesTotal) {
        try {
            var percent = Math.ceil((bytesLoaded / bytesTotal) * 100);
            upload.debug(percent);
            var progress = new FileProgress(file, this.customSettings.progressTarget);
            progress.setProgress(percent);
            progress.setStatus("正在上传，请稍候... " + percent + "%");

        } catch (ex) {
            upload.debug(ex);
        }
    }

    return upload;
}

function CustomUploadFileInit(
    panel,
    fileSizeLimit,
    IsCreateThumbnail,
    onchange,
    onsubmit,
    oncomplete,
    onerror) {

    var uploadOption =
        {
            // 提交目标
            action: "/Home/UploadImgByWebService",
            data: { "ASPSESSID": "", "fileSizeLimit": fileSizeLimit, "createThumbnail": IsCreateThumbnail },
            // 自动提交
            autoSubmit: true,
            // 选择文件之后…
            onChange: function (file, extension) {
                if (new RegExp(/(jpg)|(jpeg)|(bmp)|(gif)|(png)/i).test(extension)) {
                    $("#filepath").val(file);
                } else {
                    onerror("只限上传图片文件，请重新选择！");
                    return false;
                }
            },
            // 开始上传文件
            onSubmit: function (file, extension) {
                if (onsubmit != null) {
                    onsubmit(file, extension);
                }
            },
            // 上传完成之后
            onComplete: function (file, response) {
                if (response.indexOf("imgUseType") != -1) {
                    if (oncomplete != null) {
                        var backData = eval("(" + response + ")");
                        var fileUrl = backData["file_url"];
                        oncomplete(fileUrl);
                    }
                }
                else {
                    onerror(response);
                }
            }
        }
    var oAjaxUpload = new AjaxUpload(panel, uploadOption);
}